#include "Melody.h"

Melody::Melody(int8_t speaker_pin)
{ 
	speakerPin = speaker_pin;
	pinMode(speakerPin, OUTPUT);
}

void Melody::PlayStartup()
{
	this->length = 3; // the number of notes
	char notes[10] = "bbb"; // a space represents a rest
int8_t beats[10]= {3,1,1};
int tempo =90;

for (int i = 0; i < length; i++) {
	if (notes[i] == ' ') {
		delay(beats[i] * tempo); // rest
	} else {
		playNote(notes[i], beats[i] * tempo);
	}

	// pause between notes
	delay(tempo / 2);
}
}	
		
	
void Melody::PlaySuccess()
{
	 this->length = 3; // the number of notes
	char notes[10] = "cab"; // a space represents a rest
	int8_t beats[10]= {1,1,1};
	int tempo =100;
	
	for (int i = 0; i < length; i++) {
		if (notes[i] == ' ') {
			delay(beats[i] * tempo); // rest
		} else {
			playNote(notes[i], beats[i] * tempo);
		}

		// pause between notes
		delay(tempo / 2);
	}
}	
	
void Melody::PlayFailure()
{
	 this->length = 2; // the number of notes
	 char notes[10] = "cc"; // a space represents a rest
	 int8_t beats[10]= {1, 1};
	 int tempo = 100;
 
	 for (int i = 0; i < length; i++) {
		 if (notes[i] == ' ') {
			 delay(beats[i] * tempo); // rest
		 } else {
			 playNote(notes[i], beats[i] * tempo);
		 }

		 // pause between notes
		 delay(tempo / 2);
	 }
}	
	
void	Melody:: playNote(char note, int duration)
{
	char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
	int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };

// play the tone corresponding to the note name
	for (int i = 0; i < 8; i++)
	{
		if (names[i] == note)
		{
			playTone(tones[i], duration);
		}
	}
}

void Melody::playTone(int tone, int duration)
{
	for (long i = 0; i < duration * 1000L; i += tone * 2) 
	{
		digitalWrite(speakerPin, HIGH);
		delayMicroseconds(tone);
		digitalWrite(speakerPin, LOW);
		delayMicroseconds(tone);
	}
}
